﻿using MSSClient.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MSSClient 
{

    public class FtpHelper
    {
        public static readonly FtpHelper Instance = new FtpHelper();

        /// <summary>  
        /// 取得文件名  
        /// </summary>  
        /// <param name="ftpPath">ftp路径</param>  
        /// <returns></returns>  
        public string[] GetFilePath(string userId, string pwd, string ftpPath)
        {
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(userId, pwd);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                reqFTP.UsePassive = false;
                reqFTP.KeepAlive = false;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string line = reader.ReadLine();
                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    line = reader.ReadLine();
                }
                result.Remove(result.ToString().LastIndexOf('\n'), 1);
                reader.Close(); 
                response.Close();
                return result.ToString().Split('\n');
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
                Console.WriteLine("Exception caught: {0}", ex);
                downloadFiles = null;
                return downloadFiles;
               
            }
        }

        public void Delete(string userId, string pwd, string ftpPath, string fileName)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileName));
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(userId, pwd);
                reqFTP.UsePassive = false;
                FtpWebResponse listResponse = (FtpWebResponse)reqFTP.GetResponse();
                string sStatus = listResponse.StatusDescription;
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
                throw ex;
            }
        }

        //在ftp服务器创建文件夹
        public void MakeDir(string userId, string pwd, string ftpPath)
        {
            //DirectoryIsExist()返回false 表示ftpPath下的路径不存在，执行创建文件夹的操作
            if (DirectoryIsExist(userId, pwd, ftpPath))
            {
                return;
            }

            FtpWebRequest reqFTP;
            //创建文件夹 一次只能创建一个
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(userId, pwd);
                reqFTP.UsePassive = false;
                FtpWebResponse listResponse = (FtpWebResponse)reqFTP.GetResponse();
                string sStatus = listResponse.StatusDescription;
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
                Console.Write(ex.ToString());
            }
        }

        //判断ftp服务器中指定路径下的文件夹是否存在
        public bool DirectoryIsExist(string userId, string pwd, string ftpPath)
        {
            String[] strArrRes = GetFilePath(userId, pwd, ftpPath);

            //文件夹不存在返回false
            if (strArrRes == null)
            {
                return false;
            }
            //存在返回true
            else
            {
                return true;
            }
        }

        //补单删除图片
        public void deleteImage(string userId, string pwd, string ftpIp, string ftpPath)
        {
            try
            {
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpIp + "/" +ftpPath));
                
                reqFTP.Credentials = new NetworkCredential(userId, pwd);
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                
               string result = String.Empty;
               FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
               long size = response.ContentLength;
               Stream datastream = response.GetResponseStream();
               StreamReader sr = new StreamReader(datastream);
               result = sr.ReadToEnd();
               sr.Close();
               datastream.Close();
               response.Close();
               //Buffer.Log(string.Format("Ftp文件{1}删除成功！", DateTime.Now.ToString(), fileName));
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
                throw ex;
            }
        }

        //从ftp服务器上下载-系统更新文件，或其他文件 
        public void Download(string userId, string pwd, string ftpPath, string filePath, string fileName)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
                reqFTP.Credentials = new NetworkCredential(userId, pwd);
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
               // reqFTP.UsePassive = false;
                reqFTP.UsePassive = false;
                reqFTP.KeepAlive = true;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();

                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];
                readCount = ftpStream.Read(buffer, 0, bufferSize);

                if (!Directory.Exists(filePath))//判断文件夹是否存在 filePath为文件保存的路径
                {
                    Directory.CreateDirectory(filePath);//不存在则创建文件夹
                }
                FileStream outputStream = new FileStream(filePath + "/" + fileName, FileMode.Create);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                //MessageBox.Show("文件下载100%！");
                ftpStream.Close();
                outputStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
                MessageBox.Show(ex.Message);
                return;
            }
        }

        //下载文件
        public void NewDownLoadFile(string userId, string pwd, string ftpPath, string filePath,int ftpPort, string ipHost, string filename)
        {
            try
            {
                FTPClient fc = new FTPClient(ipHost, ftpPath, userId, pwd, ftpPort);
                fc.GetNoBinary(filename, filePath, filename);//下载刚刚上传的文件，以获取文件大小，判断是否为0kb
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
                MessageBox.Show(ex.Message);
                return;
            }
        }

        //下载更新文件
        public int DownLoadUpDataEXE(string userId, string pwd, string ftpPath, string filePath, int ftpPort, string ipHost, string filename)
        {
            try
            {
                FTPClient fc = new FTPClient(ipHost, ftpPath, userId, pwd, ftpPort);
                fc.GetNoBinary(filename, filePath, filename);
                return 1;
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
                MessageBox.Show(ex.Message);
                return 0;
            }
        }

        ///下载方法-20171227
        public String donwLoadFile(string ftpIp, int ftpPort, string ftpUserName, string ftpPassword, int mode,string[] fileInfo,string path)
        {
            string resultStr = "";
            ftpUtils ftp = new ftpUtils(ftpIp, ftpPort, ftpUserName, ftpPassword, mode);
            try
            {
                if (ftp.Connect())
                {
                    if (fileInfo.Length.Equals(4))
                    {
                        ftp.ChangeDir(fileInfo[0]); //跳转到根目录
                        ftp.ChangeDir(fileInfo[1]); //跳转一级目录
                        ftp.ChangeDir(fileInfo[2]); //跳转二级目录
                    }
                    else if(fileInfo.Length.Equals(6))
                    {
                        ftp.ChangeDir(fileInfo[0]); //跳转到根目录
                        ftp.ChangeDir(fileInfo[1]); //跳转一级目录
                        ftp.ChangeDir(fileInfo[2]); //跳转二级目录
                        ftp.ChangeDir(fileInfo[3]); //跳转三级目录
                        ftp.ChangeDir(fileInfo[4]); //跳转四级目录
                    }
                    
                    //下载文件
                    ftp.Connect();
                    ftp.OpenDownload(fileInfo[fileInfo.Length - 1], path + "\\" + fileInfo[fileInfo.Length - 1]);
                    //ftp.DoDownload();
                    while (ftp.DoDownload() > 0)
                    {
                        //int perc = (int)(((ftp.BytesTotal) * 100) / ftp.FileSize);
                        //Console.WriteLine(perc.ToString() + "%<br/>");
                    }
                    ftp.Disconnect();
                }
                else
                {
                    CommonUtil.WriteLogStr(ftp.errormessage, "donwLoadFile");
                    resultStr = ftp.errormessage;
                    return resultStr;
                }
                return resultStr;
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
                //MessageBox.Show("下载出错，错误原因：/n" + ftp.errormessage);
                resultStr = ftp.errormessage;
                return resultStr;
            }
        }

        //新的上传文件方法-20171226
        public int newUploadFun(string ftpIp, int ftpPort, string ftpUserName, string ftpPassword, int mode, List<String> rootDir, string imageCode, string ImageUrl)
        {
            ftpUtils ftp = new ftpUtils(ftpIp, ftpPort, ftpUserName, ftpPassword, mode);
            int upState = 0;
            try
            {
                //连接测试
                if (ftp.Connect())
                {
                    //建立文件夹  三级
                    //ftp.ChangeDir(rootDir);//跳转到根目录
                    //ftp.MakeDir(onedir);   //创建一级目录
                    //ftp.ChangeDir(onedir); //跳转一级目录
                    //ftp.MakeDir(twoDir);//创建二级目录 根据当前日期 如：20180108
                    //ftp.ChangeDir(twoDir);//跳转二级目录
                    //建立文件夹  五级 image/34/2018/TY..../20180912/图像:  根目录/省编/年份/单号/日期/图像
                    ftp.ChangeDir(rootDir[0]); //跳转到根目录
                    ftp.MakeDir(rootDir[1]);   //创建一级目录
                    ftp.ChangeDir(rootDir[1]); //跳转一级目录
                    ftp.MakeDir(rootDir[2]);   //创建二级目录
                    ftp.ChangeDir(rootDir[2]); //跳转二级目录
                    ftp.MakeDir(rootDir[3]);   //创建三级级目录
                    ftp.ChangeDir(rootDir[3]); //跳转三级级目录
                    ftp.MakeDir(rootDir[4]);   //创建四级目录 根据当前日期 如：20180108
                    ftp.ChangeDir(rootDir[4]); //跳转四级目录
                    //上传文件
                    ftp.Connect();
                    FileInfo fileInf = new FileInfo(ImageUrl);
                    if (ftp.OpenUpload(ImageUrl, imageCode + fileInf.Name))
                    {
                        while (ftp.DoUpload() > 0)
                        {
                            //int perc = (int)(((ftp.BytesTotal) * 100) / ftp.FileSize);
                            //Console.WriteLine(perc.ToString() + "%<br/>");
                        }
                    }
                    else
                    {
                        return upState;
                    }
                    ftp.Disconnect();
                    upState = 1;
                }
                //连接失败，说明网络不通
                else
                {
                    if (ftp.response.Equals(555)) upState = 2;
                    CommonUtil.WriteLogStr(ftp.errormessage, "newUploadFun");
                    return upState;
                }
            }
            catch (Exception ex)
            {  
                CommonUtil.WriteLog(ex);
            }
            return upState;
        }

        //新的补单删除方法
        public void newDeleteImage()
        {

        }
    }

}
